/**
 * create by young (young2f@outlook.com) on 2020/11/7
 * 表单类
 */


'use strict';
import React from 'react';
import ComponentBase from './ComponentBase';
import {Card, DatePicker, Icon, Input, InputNumber, Popconfirm, Select, Switch, Tag, Tooltip} from 'antd';
import {FormField} from 'antd-extra';
import moment from 'moment';
import 'moment/locale/zh-cn';
import MaterialElement from "../../routes/finance/modal/MaterialElement";

moment.locale('zh-cn');
const _ = require('lodash');
const {TextArea} = Input;
const {Option} = Select;
const {RangePicker} = DatePicker;
export default class FormBase extends ComponentBase {
  constructor(props) {
    super(props);
    this.props = props;
  }

  getTax(amount = 0, taxRate = '0%') {
    switch (taxRate) {
      case '0%':
        return amount;
      case '13%':
        return (amount / 1.13 * 0.13).toFixed(2);
      case '9%':
        return (amount / 1.09 * 0.09).toFixed(2);
      case '6%':
        return (amount / 1.06 * 0.06).toFixed(2);
      case '3%':
        return (amount / 1.03 * 0.03).toFixed(2);
      case '1%':
        return (amount / 1.01 * 0.01).toFixed(2);
      default:
        return 0;
    }
  }

  taxRateOption = [
    "13%", "9%", "6%", "3%", "1%", "0%"
  ];
  taxRateOption1 = [
    "13%", "9%", "6%", "3%", "1%"
  ];

  getDiscardTableColumns = () => {

    return [
      {
        title: '物料名称', dataIndex: 'name', key: 'name', render: (value, record) => {
          const {code, name} = record;
          return <MaterialElement code={code} name={name}></MaterialElement>;
        }
      },

      {title: '物料形态', dataIndex: 'subcategory', key: 'subcategory'},
      {title: '物料规格', dataIndex: 'spec', key: 'spec'},
      {title: '物料类型', dataIndex: 'type', key: 'type'},
      {title: '物料编号', dataIndex: 'number', key: 'number'},
      {title: '单价', dataIndex: 'price', key: 'price'},
      {title: '采购数量', dataIndex: 'count', key: 'count'},
      {title: '报废数量', dataIndex: 'discardCount', key: 'discardCount'},
      // {title: '日的', dataIndex: 'target', key: 'target'},
      {title: '供应商', dataIndex: 'vendor', key: 'vendor'},
      // {title: '采购类型', dataIndex: 'materialType', key: 'materialType'},
      {title: '采购公司', dataIndex: 'division', key: 'division'},
      {
        title: '审核状态', dataIndex: 'reviewStatus', key: 'reviewStatus', render: (value, record) => {
          const {reviewStatus = '待审核'} = record;
          let temp = <Tag color={'#33d'}>{'待审核'}</Tag>;
          temp = reviewStatus === '驳回' ? <Tag color={'#d33'}>{'驳回'}</Tag> : temp;
          temp = reviewStatus === '同意' ? <Tag color={'#3d3'}>{'同意'}</Tag> : temp;
          return temp;
        }
      },
      {
        title: '创建日期', dataIndex: 'createdTs', key: 'createdTs', render: value => {
          return <div>{moment(value).format('YYYY-MM-DD')}</div>;
        }
      }
    ];

  };


  model2labels = (model) => {
    const labels = [];
    _.map(model, (value, key) => {
      const {enableArea, _type} = value;
      if (_type !== 'array') {
        value['key'] = key;
        labels.push(value);
      }
    });
    return labels;
  };
  getPicCard = (files) => {
    const temp = [];
    _.map(files, file => {
      temp.push(<Card
        hoverable
        style={{width: 640}}
        cover={<img alt="example" src={file.preview}/>}
      >

      </Card>);
    });
    return temp;
  };

  getCode(prefix) {
    const time = moment()
      .format('YYMMDDHHmmss');
    // const size = 4;
    // const id = uuid.v4();
    // id.toString()
    //   .replace(/\-/g, '');
    // const temp = id.slice(0, size)
    //   .toUpperCase();
    // return `${prefix}${time}${temp}`;
    return `${prefix}${time}`;
  }

  getUploadPicButton() {
    return <div>
      <Icon type="plus"/>
      <div className="ant-upload-text">上传图片</div>
    </div>;
  }

  getUploadPdfButton() {
    return <div>
      <Icon type="plus"/>
      <div className="ant-upload-text">上传PDF文件</div>
    </div>;
  }

  getSearchField = (arr, data, pro) => {
    _.map(data, (item, k) => {
      const {enableArea = [], _type, options, title = '-'} = item;
      const {key = k} = item;
      if (enableArea.includes('search')) {
        if (_type === 'number') {
          arr.push(<FormField
            label={title}
            name={`${pro}${key}`}
            key={`${pro}${key}`}
          >
            <div>
              <Tooltip title="大于：>数字；小于：<数字；等于：=数字">
                <Input style={{width: '100%'}} allowClear placeholder={`请输入${title}`}/></Tooltip>
            </div>
          </FormField>);
        }
        if (_type === 'string') {
          arr.push(<FormField
            label={title}
            name={`${pro}${key}`}
            key={`${pro}${key}`}
          >
            <Input allowClear placeholder={`请输入${title}`}/>
          </FormField>);
        }
        if (_type === 'select') {
          arr.push(<FormField
            label={title}
            name={`${pro}${key}`}
            key={`${pro}${key}`}
          >
            <Select allowClear placeholder={`请输入${title}`}>{this.getOption2(options)}</Select>
          </FormField>);
        }
        if (_type === 'date') {
          arr.push(<FormField
            label={title}
            name={`${pro}${key}`}
            key={`${pro}${key}`}
          >
            <RangePicker
              style={{width: '100%'}}
              placeholder={`请输入${title}`}
            ></RangePicker>
          </FormField>);
        }
      }
    });
  };
  getDicTableCols = (model, onCreateOrEdit, onDelete) => {
    const temp = [];
    _.map(model, (item, key) => {
      const {type, title, enableArea = []} = item;
      if (enableArea.includes('table')) {
        const {_type = type} = item;
        if (_type === "string" || _type === "number" || _type === 'select') {
          temp.push({title, dataIndex: key, key});
        } else if (_type === "boolean") {
          temp.push({
            title, dataIndex: key, key, render: value => {
              return <div>{value ? <Tag color="green">是</Tag> : <Tag color="red">否</Tag>}</div>;
            }
          });
        } else if (_type === "date") {
          temp.push({
            title, dataIndex: key, key, render: value => {
              const _value = value ? moment(value).format("YYYY-MM-DD") : "";
              return <div>{_value}</div>;
            }
          });
        } else if (_type === "time") {
          temp.push({
            title, dataIndex: key, key, render: value => {
              return <div>{moment(value).format("YYYY-MM-DD HH:mm:ss")}</div>;
            }
          });
        } else {
          temp.push({title, dataIndex: key, key});
        }
      }
    });
    onCreateOrEdit && temp.push({
      title: "操作", dataIndex: "opt", key: "opt", fixed: 'right', width: 120, render: (value, record) => {
        return (<span>
              {onCreateOrEdit && <a style={{marginRight: '6px'}}
                                    onClick={() => onCreateOrEdit(record)}
              >编辑</a>}
          {onDelete && <Popconfirm
            title="确认删除"
            onConfirm={() => onDelete(record)}
            okText="是"
            cancelText="否"
          >
            <a>删除</a>
          </Popconfirm>}
            </span>);
      }
    });
    return temp;
  };

  getDicFields = (model, record, callback) => {
    const temp = [];
    _.map(model, (item, k) => {
      const {type, title, options, required, key = k, disabled} = item;
      let initialValue = record ? record[key] : undefined;
      const {_type = type} = item;
      if (_type === "number" || _type === "countNumber") {
        temp.push(<FormField
          label={title}
          name={key}
          required={required}
          disabled={disabled}
          initialValue={initialValue}
        >
          <InputNumber onChange={() => {
            callback && callback();
          }} disabled={disabled} style={{width: '100%'}}
          ></InputNumber>
        </FormField>);
      }

      if (_type === "string") {
        temp.push(<FormField
          label={title}
          name={key}
          required={required} disabled={disabled}
          initialValue={initialValue}
        >
          <Input disabled={disabled} style={{width: '100%'}}
          ></Input>
        </FormField>);
      }
      if (_type === "boolean") {
        temp.push(<FormField
          label={title}
          name={key}
          required={required} disabled={disabled}
          initialValue={initialValue}
        >
          <Switch disabled={disabled} checkedChildren="是" unCheckedChildren="否"
                  defaultChecked={initialValue}></Switch>
        </FormField>);
      }

      if (_type === "date") {
        initialValue = record && record[key] ? moment(record[key]) : undefined;

        temp.push(<FormField
          label={title}
          name={key}
          required={required} disabled={disabled}
          initialValue={initialValue}
        >
          <DatePicker disabled={disabled}
                      style={{width: '100%'}}
          ></DatePicker>
        </FormField>);

      }

      if (_type === "select") {
        temp.push(<FormField
          label={title}
          name={key}
          required={required} disabled={disabled}
          initialValue={initialValue}
        >
          <Select style={{width: '100%'}} disabled={disabled}
          >{this.getOption2(options)}</Select>
        </FormField>);
      }
      if (_type === "memo") {
        temp.push(<FormField
          label={title}
          name={key}
          required={required} disabled={disabled}
          initialValue={initialValue}
        >
          <TextArea style={{width: '100%'}}></TextArea>
        </FormField>);
      }

    });
    return temp;
  };
  getDicSearchFields = (model, record) => {
    const temp = [];
    _.map(model, (item, k) => {
      const {type, title, options, enableArea = [], key = k} = item;
      if (enableArea.includes('search')) {
        let initialValue = record ? record[key] : undefined;
        const {_type = type} = item;
        if (_type === "number") {
          temp.push(<FormField
            label={title}
            name={key}
            initialValue={initialValue}
          >
            <InputNumber style={{width: '100%'}}
            ></InputNumber>
          </FormField>);
        }

        if (_type === "string") {
          temp.push(<FormField
            label={title}
            name={key}

            initialValue={initialValue}
          >
            <Input style={{width: '100%'}}
            ></Input>
          </FormField>);
        }
        if (_type === "boolean") {
          temp.push(<FormField
            label={title}
            name={key}

            initialValue={initialValue}
          >
            <Switch checkedChildren="是" unCheckedChildren="否"
                    defaultChecked={initialValue}></Switch>
          </FormField>);
        }

        if (_type === "date") {
          initialValue = record ? moment(record[key], "YYYY-MM-DD") : undefined;
          temp.push(<FormField
            label={title}
            name={key}
            initialValue={initialValue}
          >
            <DatePicker
              style={{width: '100%'}}
            ></DatePicker>
          </FormField>);

        }

        if (_type === "select") {
          temp.push(<FormField
            label={title}
            name={key}
            initialValue={initialValue}
          >
            <Select style={{width: '100%'}}
            >{this.getOption2(options)}</Select>
          </FormField>);
        }
      }
    });
    return temp;
  };
  getInboundLotCols = () => {
    return [
      {
        title: "物料", dataIndex: 'code', key: 'code', fixed: 'left', render: (value, record) => {
          const {code, name, unit} = record;
          return this.getProductionElement(code, name, unit);
        }
      },
      {
        title: '入库数量',
        dataIndex: 'inboundCount',
        key: 'inboundCount'

      },
      {
        title: '入库时间',
        dataIndex: 'lotDate',
        key: 'lotDate',
        render: value => {
          return <div>{moment(value).format('YYYY-MM-DD')}</div>;
        }
      },
      {
        title: '操作者',
        dataIndex: 'createUsername',
        key: 'createUsername'
      }
    ];
  };
  getOutboundLotCols = () => {
    return [
      {title: '批次编码', key: 'lotCode', dataIndex: "lotCode", fixed: "left"},
      {title: '客户', key: 'customer', dataIndex: "customer"},
      {title: '品名', key: 'prodName', dataIndex: "prodName"},
      {title: '编号', key: 'prodCode', dataIndex: "prodCode"},
      {title: '出货日期', key: 'outboundDate', dataIndex: "outboundDate"},
      {title: '出货数量', key: 'outboundCount', dataIndex: "outboundCount"},
      {title: '运费', key: 'shippingFee', dataIndex: "shippingFee"},
      {title: '包装', key: 'pkg', dataIndex: "pkg"},
      {title: '发货方式', key: 'deliverWay', dataIndex: "deliverWay"},
      {title: '承运人', key: 'shippingMan', dataIndex: "shippingMan"}];
  };

  getOption2 = (list) => {
    let map = list ? list.map(item => {
      return (
        <Option value={item}>{item}</Option>
      );
    }) : null;
    return map;
  };
  getModelOption = (model, key) => {
    const temp = model[key];
    let map = temp && temp.options ? temp.options.map(item => {
      return (
        <Option value={item}>{item}</Option>
      );
    }) : null;
    return map;
  };

  getDynamicLabelCols(labels) {
    // if (!model) return []
    // const result = [];
    // const temp = [];
    // const {labels} = model;
    // _.map(model, (item, key) => {
    //   if (key !== 'labels') {
    //     item.key = key;
    //     temp.push(item)
    //   }
    // });
    // labels && labels.length && labels.map(item => {
    //   temp.push(item);
    // });
    const result = [];
    _.map(labels, item => {
      const {desc, key, inputType, selectOption, enableArea} = item;
      // let render = inputType.toString().toLowerCase() === 'select' ? (value) => {
      //   const v = _.find(selectOption, item => item.value === value);
      //   const _v = v ? v.label : value;
      //   return <div>{_v}</div>;
      // } : undefined;

      let render = inputType.toString().toLowerCase() === 'switch' ? (value) => {
        const v = value ? '是' : '否';
        return <div>{v}</div>;
      } : undefined;
      render = inputType.toString().toLowerCase() === 'date' ? (value) => {
        return <div>{moment(value).format('YYYY-MM-DD')}</div>;
      } : render;
      // const _key = isInitKey ? key : `labels.${key}`;
      _.includes(enableArea, 'table') && result.push({
        title: desc,
        dataIndex: key,
        key: key,
        ellipsis: true,
        render
      });
    });
    // _.map(model, (item, key) => {
    //   if (key !== 'labels') {
    //     const {enableArea, inputType} = item;
    //     item.title = item.label;
    //     item.key = key;
    //     item.dataIndex = key;
    //     _.includes(enableArea, 'table') && result.push(item);
    //   }
    // })
    //
    // labels && labels.length && labels.map(item => {
    //   const {label, key, inputType, selectOption, enableArea} = item;
    //   let render = inputType.toString().toLowerCase() === 'select' ? (value) => {
    //     const v = _.find(selectOption, item => item.value === value);
    //     const {label} = v;
    //     return <div>{label}</div>;
    //   } : undefined;
    //
    //   render = inputType.toString().toLowerCase() === 'switch' ? (value) => {
    //     const v = value ? '是' : '否';
    //     return <div>{v}</div>;
    //   } : render;
    //
    //   // const _key = isInitKey ? key : `labels.${key}`;
    //
    //   _.includes(enableArea, 'table') && result.push({
    //     title: label,
    //     // dataIndex: _key,
    //     dataIndex: key,
    //     // key: _key,
    //     key: key,
    //     ellipsis: true,
    //     render
    //   });
    // });
    return result;
  }

  /**
   * 获取动态表单数据的详情
   * @param dynamicLabels
   * @returns {[]}
   */
  getDLabelDetail(dLabels, values) {
    console.log('get dlabels detail', dLabels, values);
  }


  getModelSearchFields = (model, record) => {
    const temp = [];
    _.map(model, (item, k) => {
      const {type, title, options, key = k, enableArea = []} = item;
      if (enableArea.includes('search')) {
        let initialValue = record ? record[key] : undefined;
        const {_type = type} = item;
        if (_type === "number") {
          temp.push(<FormField
            label={title}
            name={key}
            initialValue={initialValue}
          >
            <InputNumber style={{width: '100%'}}
            ></InputNumber>
          </FormField>);
        }

        if (_type === "string") {
          temp.push(<FormField
            label={title}
            name={key}

            initialValue={initialValue}
          >
            <Input style={{width: '100%'}}
            ></Input>
          </FormField>);
        }
        if (_type === "boolean" || _type === "switch") {
          temp.push(<FormField
            label={title}
            name={key}
            initialValue={initialValue}
          >
            <Switch checkedChildren="是" unCheckedChildren="否"
                    defaultChecked={initialValue}></Switch>
          </FormField>);
        }

        if (_type === "date") {
          initialValue = record ? moment(record[key], "YYYY-MM-DD") : undefined;
          temp.push(<FormField
            label={title}
            name={key}
            initialValue={initialValue}
          >
            <DatePicker
              style={{width: '100%'}}
            ></DatePicker>
          </FormField>);

        }
        if (_type === "dateRange") {
          temp.push(<FormField
            label={title}
            name={key}
          >
            <RangePicker
              style={{width: '100%'}}
              placeholder={`请输入${title}`}
            ></RangePicker>
          </FormField>);

        }
        if (_type === "select") {
          temp.push(<FormField
            label={title}
            name={key}
            initialValue={initialValue}
          >
            <Select style={{width: '100%'}}
            >{this.getOption2(options)}</Select>
          </FormField>);
        }
      }
    });
    return temp;
  };

  getTableColumns = (model) => {

    if (!model) return [];

    const temp = [];
    _.map(model, (item, key) => {
      const {enableArea, title, _type, tag} = item;
      if (_.includes(enableArea, "table")) {
        item.title = title;
        item.key = key;
        item.dataIndex = key;
        item.ellipsis = true;
        _type === 'switch' ? item.render = (record) => {
          const value = record ? "是" : "否";
          return <div>{value}</div>;
        } : undefined;

        _type === 'date' || _type === 'dateRange' ? item.render = (value) => {
          const _value = value ? moment(value).format('YYYY-MM-DD') : '';
          return <div>{_value}</div>;
        } : undefined;
        if (tag) {
          item.render = (value) => {
            const color = tag[value] ? tag[value] : "#222";
            return <Tag color={color}>{value}</Tag>;
          };
        }
        temp.push(item);
      }
    });

    temp.push(
      {
        title: '创建者',
        dataIndex: 'createUsername',
        key: 'createUsername',
        width: 120
      },
      {
        title: '创建时间',
        dataIndex: 'createdTs',
        key: 'createdTs',
        width: 160,
        render: value => {
          return <div>{moment(value).format('YYYY-MM-DD hh:mm:ss')}</div>;
        }
      }
    );
    return temp;
  };
}
